# -*- coding=utf-8 -*-

import markdown2

from django.contrib import admin
from .models import Article
from autohome.forms import ArticleForm


# Register your models here.
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    form = ArticleForm

    fields = ('id', 'url', 'status', 'title', 'abstract', 'content', 'create_time')
    list_display = ('url', 'title', 'abstract')
    list_display_links = ('url', 'title')

    change_form_template = 'custom_editor_page.html'

    def save_model(self, request, obj, form, change):
        content = obj.content
        obj.content = content
        super(ArticleAdmin, self).save_model(request, obj, form, change)

    def change_view(self, request, object_id, form_url = '', extra_context = None):
        extra_context = extra_context or {}
        article = Article.objects.filter(id = object_id).first()
        extra_context['article'] = article
        extra_context['content'] = markdown2.markdown(text = article.content, extras = {
            'tables': True,
            'wiki-tables': True,
            'fenced-code-blocks': True,
        })
        return super(ArticleAdmin, self).change_view(
            request, object_id, form_url, extra_context = extra_context,
        )

        # def get_urls(self):
        #     urls = super(ArticleAdmin, self).get_urls()
        #     cus_urls = [
        #         # url(r'^add/$', self.cus_view),
        #         url(r'^\d+/change/$', self.cus_view),
        #     ]
        #     print ('urls:%s' % urls)
        #     return cus_urls + urls
        #
        # def cus_view(self, request):
        #     print('path:%s' % request.path)
        #     # ...
        #     # context = dict(
        #     #         # Include common variables for rendering the admin template.
        #     #         self.admin_site.each_context(request),
        #     #         # Anything else you want in the context...
        #     #         key = Article(),
        #     # )
        #     article = Article()
        #     article.title = 'This is admin'
        #     context = {
        #         'article': article
        #     }
        #     return TemplateResponse(request, "sometemplate.html", context)

        # def change_view(self, request, object_id, form_url = '', extra_context = None):
        #     print('path:%s id:%s form_url:%s' % (request.path, object_id, form_url))
        #     return self.changeform_view(request, object_id, form_url, extra_context)
